package com.gdface.admin.gdface_attend;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
import com.pefis.natives.Ast2600JNI;
import com.pefis.natives.IUsbConnState;
import com.pefis.natives.PfsBioInfo;

import com.gdface.admin.gdface_attend.utils.LogUtils;

import java.io.File;

public class MainActivity extends AppCompatActivity {


    private String mStrDevId;
    private String mStrDevName;
    private int[] m_nContextID = new int[1];
    int cirlation = 0;

    private Button bt_initSDK, bt_StartFace;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏标题
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏

        setContentView(R.layout.activity_main);

        Ast2600JNI.createInstance(this, m_IConnectionHandler);
        PfsBioInfo.createInstance(this);


        bt_initSDK = (Button) findViewById(R.id.main_bt_init);
        bt_StartFace = (Button) findViewById(R.id.main_bt_start);

        bt_initSDK.setOnClickListener(onClickListener);
        bt_StartFace.setOnClickListener(onClickListener);

        setBTEnabled(1);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.main_bt_init://初始化
                    InitDeviceEntity();
                    break;

                case R.id.main_bt_start://开始人脸识别
                    Intent intent_start = new Intent(MainActivity.this, IdentifyActivity.class);
                    startActivity(intent_start);
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        // Don't forget to shutdown!
        Ast2600JNI.getInstance().pisCloseDevice(m_nContextID[0]);
        Ast2600JNI.getInstance().pisDestroyContext(m_nContextID[0]);
        super.onDestroy();
    }


    /**
     * 设置按钮状态
     *
     * @param res 0成功   1失败
     */
    private void setBTEnabled(int res) {
        if (res == 0) {
            bt_initSDK.setEnabled(false);
            bt_StartFace.setEnabled(true);
//            bt_enroll.setEnabled(true);

            bt_initSDK.setTextColor(this.getResources().getColor(R.color.gray));
            bt_StartFace.setTextColor(this.getResources().getColor(R.color.White));
//            bt_enroll.setTextColor(this.getResources().getColor(R.color.White));
        } else if (1 == res) {
            bt_initSDK.setEnabled(true);
            bt_StartFace.setEnabled(false);
//            bt_enroll.setEnabled(false);

            bt_initSDK.setTextColor(this.getResources().getColor(R.color.White));
            bt_StartFace.setTextColor(this.getResources().getColor(R.color.gray));
//            bt_enroll.setTextColor(this.getResources().getColor(R.color.gray));
        }
    }


    private void InitDeviceEntity() {
        int i = InitDevice();
        switch (i) {
            case -1://无设备
                setBTEnabled(1);
                Toast.makeText(this, "设备检测失败，请确认设备已连接!", Toast.LENGTH_SHORT).show();
                break;
            case 0://设备连接失败
                cirlation++;
                if (5 > cirlation) {
                    InitDeviceEntity();
                } else {
                    setBTEnabled(1);
                    cirlation = 0;
                    Toast.makeText(this, "设备初始化失败!", Toast.LENGTH_SHORT).show();
                }

                break;
            case 1://设备连接成功
                setBTEnabled(0);
                Toast.makeText(this, "设备初始化成功!", Toast.LENGTH_SHORT).show();
                break;
        }
    }


    /**
     * 初始化设备   -1 无设备 0 设备连接失败 1 设备连接成功
     *
     * @return
     */
    private int InitDevice() {
        String str;
        int res_sum = 0;
        if (!Ast2600JNI.getInstance().IsInit()) {
            if (Ast2600JNI.getInstance().InitDevice()) {
                //
            } else {
                str = "Failed init usb!";
            }
        } else if (!Ast2600JNI.getInstance().IsEnumerated()) {
            //preInit();
        } else {
            int vnRet = 0;

            vnRet = Ast2600JNI.getInstance().pisCreateContext(m_nContextID);
            if (vnRet != PfsBioInfo.PFSBIO_OK) {
                Log.i("hwwlog", "pisCreateContext  = " + vnRet);
                return 0;
            }
            PfsBioInfo.getInstance().mContextID = m_nContextID[0];

            m_nDevId = m_pStrDevId;
            if (m_nDevId == null) {
                Ast2600JNI.getInstance().ReInit();
                return 0;
            }
            vnRet = Ast2600JNI.getInstance().pisOpenDevice(m_nContextID[0], m_nDevId.getBytes(), PfsBioInfo.INIT_DATA_PATH.getBytes());
            if (vnRet != PfsBioInfo.PFSBIO_OK) {

                Log.i("hwwlog", "pisOpenDevice  = " + vnRet);
                Ast2600JNI.getInstance().pisDestroyContext(m_nContextID[0]);

                return 0;
            }

            DeviceParamsDate();

            res_sum = 1;
            return 1;
        }
        return res_sum;
    }


    private int InitDevice_old() {



        int vnRet;
        int i = 0;
        byte[] vByteDeviceDescription = new byte[256];
        byte[] vDeviceIdentifier = new byte[256];

        vnRet = Ast2600JNI.getInstance().pisEnumerateDevice(i, vDeviceIdentifier, vByteDeviceDescription);
        if (vnRet == PfsBioInfo.PFSBIO_OK) {
            mStrDevId = Ast2600JNI.ByteArrayUtf8ToString(vDeviceIdentifier);
            mStrDevName = Ast2600JNI.ByteArrayUtf8ToString(vByteDeviceDescription);
        } else {
            LogUtils.i("检测当前存在的设备错误 : vnRet = " + vnRet);
            mStrDevId = "";
            mStrDevName = "";
            return -1;
        }
        LogUtils.i("检测当前存在的设备  成  功   = " + mStrDevId + "   name = " + mStrDevName);

        if (!Ast2600JNI.getInstance().IsInit()) {
            if (Ast2600JNI.getInstance().InitDevice()) {
                //
            } else {
                //mHandler.obtainMessage(MSG_DRAW_TXT, str).sendToTarget();

            }
        } else if (!Ast2600JNI.getInstance().IsEnumerated()) {
            //preInit();

        }

        PfsBioInfo.getInstance().mEnrollID = -1;
        vnRet = Ast2600JNI.getInstance().pisCreateContext(m_nContextID);

        if (vnRet != PfsBioInfo.PFSBIO_OK) {
            LogUtils.i("USB口设备检测错误 : vnRet = " + vnRet);
            return 0;
        }

        PfsBioInfo.getInstance().mContextID = m_nContextID[0];

        vnRet = Ast2600JNI.getInstance().pisOpenDevice(m_nContextID[0], mStrDevId.getBytes(), PfsBioInfo.INIT_DATA_PATH.getBytes());
        if (vnRet != PfsBioInfo.PFSBIO_OK) {
            Ast2600JNI.getInstance().pisDestroyContext(m_nContextID[0]);
            LogUtils.i("打开摄像头等设备错误 : vnRet = " + vnRet);
            return 0;
        }

        DeviceParamsDate();

        return 1;
    }

    public void DeviceParamsDate() {
        Ast2600JNI.getInstance().pisFcClearTptArray(PfsBioInfo.getInstance().mContextID);
        try {
            // Get Face process parameters
            Ast2600JNI.getInstance().pisGetInfo(m_nContextID[0], PfsBioInfo.PFSBIO_FACE_PARAM_KIND_IMG_W, PfsBioInfo.getInstance().face_img_w);
            Ast2600JNI.getInstance().pisGetInfo(m_nContextID[0], PfsBioInfo.PFSBIO_FACE_PARAM_KIND_IMG_H, PfsBioInfo.getInstance().face_img_h);
            Ast2600JNI.getInstance().pisGetInfo(m_nContextID[0], PfsBioInfo.PFSBIO_FACE_PARAM_KIND_TEMPLATE_SIZE, PfsBioInfo.getInstance().enroll_template_size);
            Ast2600JNI.getInstance().pisGetInfo(m_nContextID[0], PfsBioInfo.PFSBIO_FACE_PARAM_KIND_FEATURE_SIZE, PfsBioInfo.getInstance().match_feature_size);
            Ast2600JNI.getInstance().pisGetInfo(m_nContextID[0], PfsBioInfo.PFSBIO_FACE_PARAM_KIND_ENROLL_FACE_COUNT, PfsBioInfo.getInstance().enroll_face_count);
            // Ast2600JNI.getInstance().pisGetInfo(m_nContextID[0],PfsBioInfo.PFSBIO_FACE_PARAM_KIND_FACE_PROC_VER,
            // PfsBioInfo.getInstance().face_proc_version);

            PfsBioInfo.getInstance().malloc_vars(this);
            LoadTemplateFiles();

//            getAllFiles(PfsBioInfo.TEMPLATE_DB_PATH);
            // convertData();

        } catch (Exception e) {
            // e.printStackTrace();
            Ast2600JNI.getInstance().pisCloseDevice(m_nContextID[0]);
            Ast2600JNI.getInstance().pisDestroyContext(m_nContextID[0]);
        }

        Log.i("hwwlog","enroll_template_size = "+PfsBioInfo.getInstance().enroll_template_size[0]+"\nmatch_feature_size = "+PfsBioInfo.getInstance().match_feature_size[0]);
    }

    /**
     * 检测或创建特征码文件夹  设置模型数据
     */
    public void LoadTemplateFiles() {
        File m_File = new File(PfsBioInfo.TEMPLATE_DB_PATH);

        if (!m_File.isDirectory()) {
            if (!m_File.mkdir()) {
                return;
            }
        }

        File mPhotoDir = new File(PfsBioInfo.PHOTO_DB_PATH);
        if (mPhotoDir.isDirectory() == false) {
            if (mPhotoDir.mkdir() == false) {
                return;
            }
        }

        String[] vFileNameList = m_File.list();
        int vFileCounts = vFileNameList.length;
        int vnTemplateID;

        int vReadRet;
        int vnRet = 0;
        int res_sum = 0;
        long time_ = 0;
        time_ = System.currentTimeMillis();
        while (vFileCounts != 0) {
            vReadRet = PfsBioInfo.getInstance().ReadByteFromFile(
                    PfsBioInfo.TEMPLATE_DB_PATH + vFileNameList[vFileCounts - 1],
                    PfsBioInfo.getInstance().m_pTemplate,
                    PfsBioInfo.getInstance().enroll_template_size[0]);
            if (vReadRet == -1) {

                return;
            }
            vnTemplateID = 0;
            try {
                vnTemplateID = Integer.valueOf(vFileNameList[vFileCounts - 1]);
            } catch (Exception e) {
                e.printStackTrace();
            }

            vnRet = Ast2600JNI.getInstance().pisFcSetAtTptArray(m_nContextID[0], (int) vnTemplateID, PfsBioInfo.getInstance().m_pTemplate);
            if (vnRet != PfsBioInfo.PFSBIO_OK) {
                vFileCounts -= 1;
                continue;
            }
            vFileCounts -= 1;
            res_sum++;
        }
        Log.i("hwwlog","时间差   =   "+(System.currentTimeMillis() - time_));

        Toast.makeText(MainActivity.this, "读取建模数量 " + res_sum + " 个", Toast.LENGTH_LONG).show();
    }

    //读取模板数量
    private int getAllFiles(String root) {
        int sum = 0;
        File file = new File(root);
        File files[] = file.listFiles();
        if (files != null) {
            for (File f : files) {
                if (!f.isDirectory()) {
                    sum++;
                }
            }
        }
        Toast.makeText(MainActivity.this, "读取建模数量 " + sum + " 个", Toast.LENGTH_LONG).show();
        return sum;
    }

    static String m_pStrDevId;
    static String m_pStrDevName;
    String m_nDevId;

    private void preInit(){
        String vStrDeviceDescription;
        int vnRet;
        int i=0;
        byte[] vByteDeviceDescription = new byte[256];
        byte[] vDeviceIdentifier = new byte[256];

        vnRet = Ast2600JNI.getInstance().pisEnumerateDevice(i, vDeviceIdentifier, vByteDeviceDescription);
        if (vnRet == PfsBioInfo.PFSBIO_OK) {
            m_pStrDevId = Ast2600JNI.ByteArrayUtf8ToString(vDeviceIdentifier);
            m_pStrDevName = Ast2600JNI.ByteArrayUtf8ToString(vByteDeviceDescription);
            Ast2600JNI.getInstance().SetEnumerate(true);
        } else{
            Ast2600JNI.getInstance().SetEnumerate(false);
            //ErrorDescription(PfsBioInfo.INIT_PROC,PfsBioInfo.ENUMERATE_DEVICE_FUNC,vnRet);
        }

    }

    private final IUsbConnState m_IConnectionHandler = new IUsbConnState() {
        @Override
        public void onUsbConnected() {
            String[] w_strInfo = new String[1];
            preInit();

        }

        @Override
        public void onUsbPermissionDenied() {
            // EditResult.setText("Permission denied!");

        }

        @Override
        public void onDeviceNotFound() {
            // EditResult.setText("Can not find usb device 2!");

        }
    };


}
